package com.ticket.sass.provider.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ticket.sass.common.entity.tenant.ThemeConfigEntity;
import com.ticket.sass.provider.mapper.ThemeConfigMapper;
import com.ticket.sass.provider.service.BaseService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ywb
 * @since 2024-03-26
 */
@Service
public class ThemeConfigServiceImpl extends ServiceImpl<ThemeConfigMapper, ThemeConfigEntity> implements BaseService<ThemeConfigEntity> {
    public void saveOrUpdateThemeConfig(Long cinemaId, String data, Long tenantId) {
        // 查询是否存在记录
        QueryWrapper<ThemeConfigEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cinema_id", cinemaId);
        queryWrapper.eq("tenant_id", tenantId);
        ThemeConfigEntity themeConfigEntity = getOne(queryWrapper);
        
        if (themeConfigEntity != null) {
            // 存在记录，更新 data 字段
            UpdateWrapper<ThemeConfigEntity> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("cinema_id", cinemaId);
            updateWrapper.eq("tenant_id", tenantId);
            updateWrapper.set("data", data);
            update(updateWrapper);
        } else {
            // 不存在记录，新增一条
            ThemeConfigEntity newThemeConfigEntity = new ThemeConfigEntity();
            newThemeConfigEntity.setCinemaId(cinemaId);
            newThemeConfigEntity.setData(data);
            newThemeConfigEntity.setTenantId(tenantId);
            save(newThemeConfigEntity);
        }
    }
    
    public Map<Long, String> getDataByTenant(List<Long> tenantIds) {
        if (tenantIds.size() == 0){
            return new HashMap<>();
        }
        // 创建查询条件，筛选 cinemaId 为 0
        QueryWrapper<ThemeConfigEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cinema_id", 0);
        queryWrapper.in("tenant_id", tenantIds);
        
        // 查询符合条件的所有记录
        List<ThemeConfigEntity> themeConfigEntities = list(queryWrapper);
        
        // 将查询结果转换为 Map<tenantId, data>
        return themeConfigEntities.stream()
            .collect(Collectors.toMap(ThemeConfigEntity::getTenantId, ThemeConfigEntity::getData));
    }
}
